package net.guerlab.smart.wx.api.autoconfig;

import lombok.AllArgsConstructor;
import net.guerlab.smart.wx.api.WxMaSubscribeMsgApi;
import net.guerlab.smart.wx.core.message.SendMsgResponse;
import net.guerlab.smart.wx.core.message.WxMaSubscribeMessageSendRequest;
import net.guerlab.smart.wx.service.controller.ma.AbstractWxMaSubscribeMsgController;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.*;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.lang.NonNull;

import java.util.Map;

/**
 * @author guer
 */
@Configuration
@Conditional(WxMaSubscribeMsgApiLocalServiceAutoConfigure.WrapperCondition.class)
public class WxMaSubscribeMsgApiLocalServiceAutoConfigure {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Bean
    @ConditionalOnBean(AbstractWxMaSubscribeMsgController.class)
    public WxMaSubscribeMsgApi wxMaSubscribeMsgApiLocalServiceWrapper(AbstractWxMaSubscribeMsgController controller) {
        return new WxMaSubscribeMsgApiLocalServiceWrapper(controller);
    }

    @SuppressWarnings("WeakerAccess")
    static class WrapperCondition implements Condition {

        @Override
        public boolean matches(@NonNull ConditionContext context, @NonNull AnnotatedTypeMetadata metadata) {
            try {
                return WrapperCondition.class.getClassLoader()
                        .loadClass("net.guerlab.smart.wx.service.controller.ma.AbstractWxMaSubscribeMsgController")
                        != null;
            } catch (Exception e) {
                return false;
            }
        }
    }

    @AllArgsConstructor
    private static class WxMaSubscribeMsgApiLocalServiceWrapper implements WxMaSubscribeMsgApi {

        private final AbstractWxMaSubscribeMsgController controller;

        @Override
        public Map<String, SendMsgResponse> sendMsg(String appId, WxMaSubscribeMessageSendRequest sendData) {
            return controller.sendMsg(appId, sendData);
        }
    }

}
